package com.yds.developtools.utils;

import android.Manifest;
import android.app.Application;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * HttpUrlConnection 下载文件帮助类
 *
 * 使用方法：
 * YDSHttpUrlDownloadHelper.getInstance(getApplication()).downloadFile( url, "YDS/AAA/BBB",new DownloadManager.DownloadListener() {
 *         @Override
 *         public void onProgressUpdate(long bytesRead, long fileLength) {
 *             // 更新UI显示下载进度
 *         }
 *
 *         @Override
 *         public void onDownloadSuccess(String filePath) {
 *             // 下载成功，处理文件
 *         }
 *
 *         @Override
 *         public void onDownloadFailed(String errorMessage) {
 *             // 下载失败，处理错误
 *         }
 *     }
 * );
 */
public class YDSDownloadFileHttpUrlHelper {

    private static volatile YDSDownloadFileHttpUrlHelper instance;
    private final ExecutorService executorService;
    private final Map<String, DownloadTask> taskMap;
    private final Handler mainHandler;
    private final Application context;

    private YDSDownloadFileHttpUrlHelper(Application context) {
        this.context = context;
        executorService = Executors.newCachedThreadPool();
        taskMap = new HashMap<>();
        mainHandler = new Handler(Looper.getMainLooper());
    }

    public static YDSDownloadFileHttpUrlHelper getInstance(Application context) {
        if (instance == null) {
            synchronized (YDSDownloadFileHttpUrlHelper.class) {
                if (instance == null) {
                    instance = new YDSDownloadFileHttpUrlHelper(context);
                }
            }
        }
        return instance;
    }

    /**
     * 下载文件 - 默认下载到Download文件夹
     *
     * @param fileUrl  下载文件的 URL
     * @param fileName 下载文件的名称 如：hello.txt
     * @param listener 下载监听器
     */
    public void downloadFile(String fileUrl, String fileName, DownloadListener listener) {
        downloadFile(fileUrl, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), fileName, listener);
    }

    /**
     * 下载文件 - 自定义文件夹 如：AAA/BBB/CCC
     *
     * @param fileUrl  下载文件的 URL
     * @param filePath 下载文件的路径 默认：Environment.DIRECTORY_DOWNLOADS
     * @param fileName 下载文件的名称 如：hello.txt
     * @param listener 下载监听器
     */
    public void downloadFile(String fileUrl, String filePath, String fileName, DownloadListener listener) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            throw new RuntimeException("WRITE_EXTERNAL_STORAGE PERMISSION DENIED");
        } else {
            File directory = Environment.getExternalStoragePublicDirectory(filePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            DownloadTask task = new DownloadTask(fileUrl, Environment.getExternalStoragePublicDirectory(filePath).getAbsolutePath(), fileName, listener);
            taskMap.put(fileUrl, task);
            executorService.execute(task);
        }
    }

    /**
     * 取消下载文件
     *
     * @param fileUrl 下载文件的 URL
     */
    public void cancelDownload(String fileUrl) {
        DownloadTask task = taskMap.get(fileUrl);
        if (task != null) {
            task.cancel();
            taskMap.remove(fileUrl);
        }
    }

    /**
     * 下载任务
     */
    private class DownloadTask implements Runnable {
        private final String fileUrl;
        private final String filePath;
        private final String fileName;
        private final DownloadListener listener;
        private boolean isCanceled;

        DownloadTask(String fileUrl, String filePath, String fileName, DownloadListener listener) {
            this.fileUrl = fileUrl;
            this.filePath = filePath;
            this.fileName = fileName;
            this.listener = listener;
            this.isCanceled = false;
        }

        void cancel() {
            isCanceled = true;
        }

        @Override
        public void run() {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            HttpURLConnection connection = null;

            try {
                URL url = new URL(fileUrl);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                int fileLength = connection.getContentLength();
                inputStream = connection.getInputStream();
                Log.i("YDSimon", "filePath = " + filePath + File.separator + fileName);
                outputStream = new FileOutputStream(new File(filePath, fileName));

                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead = 0;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    if (isCanceled) {
                        notifyFailure("Download canceled");
                        return;
                    }
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                    notifyProgress(totalBytesRead, fileLength);
                }

                notifySuccess();
            } catch (IOException e) {
                notifyFailure(e.getMessage());
            } finally {
                try {
                    if (inputStream != null) inputStream.close();
                    if (outputStream != null) outputStream.close();
                    if (connection != null) connection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                taskMap.remove(fileUrl);
            }
        }

        // 主线程更新进度
        private void notifyProgress(final long bytesRead, final long fileLength) {
            mainHandler.post(() -> {
                if (listener != null) {
                    int progress = (int) ((bytesRead * 100L) / fileLength);
                    listener.onProgressUpdate(progress);
                }
            });
        }

        // 主线程更新成功状态
        private void notifySuccess() {
            mainHandler.post(() -> {
                if (listener != null) {
                    listener.onDownloadSuccess(filePath + File.separator + fileName);
                }
            });
        }

        // 主线程更新失败状态
        private void notifyFailure(final String errorMessage) {
            mainHandler.post(() -> {
                if (listener != null) {
                    listener.onDownloadFailed(errorMessage);
                }
            });
        }
    }

    /**
     * 下载监听器接口
     */
    public interface DownloadListener {
        void onProgressUpdate(int progress);

        void onDownloadSuccess(String filePath);

        void onDownloadFailed(String errorMessage);
    }
}